import json
import urllib.request
import urllib.parse
import requests
import pymysql
import time

# 根据基金ID获取最新的单位净值
# string  -->  float
def get_price_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-05-14", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    if "netWorth" not in fund_info.keys():
        return 0
    return float(fund_info["netWorth"])


# 根据基金ID获取最新的多个单位净值
# string -->  [float,float, ...]
def get_many_price_by_id(fund_id, number):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-04-15", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    if "netWorthData" not in fund_info.keys():
        return []
    data = fund_info["netWorthData"]
    res = []
    for item in data[-number:]:
        res.append([item[0][5:], item[1], item[2]])
    return res



# 根据基金ID获取各种股票占比
# string  -->  [[id, name,rate], [id, name, rate], ...]
def get_position_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/position?code=" + fund_id, headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    res = []
    if "stockList" not in json.loads(response)["data"].keys():
        return res
    stock_list = json.loads(response)["data"]["stockList"]
    for item in stock_list:
        res.append([item[0], item[1], item[2]])
    return res


# 根据基金ID获得各类占比
# string  -->  [[name, rate], [name, rate], ...]
def get_rate_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/position?code=" + fund_id, headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    res = []
    if json.loads(response)["data"] is None:
        return []
    stock_list = json.loads(response)["data"]["stockList"]
    res.append(["stock", json.loads(response)["data"]["stock"]])
    res.append(["bond", json.loads(response)["data"]["bond"]])
    res.append(["cash", json.loads(response)["data"]["cash"]])
    return res


# 根据基金ID获取基金规模
# string  -->  [fund_scale, date]
def get_scale_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-05-14", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    if "netWorthDate" not in fund_info.keys():
        return [0, 0]
    return [fund_info["fundScale"], fund_info["netWorthDate"]]


# 根据参数获得周、月、年涨幅排行
# [[id, name, increase, value]]
def get_rank(rank_type, number, page):
    # rank_type == r  日涨幅
    # rank_type == z  周涨幅
    # rank_type == 1y 月涨幅
    # rank_type == jn 年涨幅
    url = "https://api.doctorxiong.club/v1/fund/rank"
    data = {
        "sort": rank_type,
        "pageIndex": page,
        "pageSize": number
    }
    headers = {
        "token": "atTPd9c8sA",
        "Content-Type": "application/json"
    }
    # 请求方式
    content = requests.post(url=url, headers=headers, data=json.dumps(data)).text
    funds = json.loads(content)["data"]["rank"]
    res = []
    for fund in funds:
        value = 0
        increase = 0
        if rank_type == "z":
            increase = fund["lastWeekGrowth"]
        elif rank_type == "1y":
            increase = fund["lastMonthGrowth"]
        elif rank_type == "jn":
            increase = fund["lastYearGrowth"]
        elif rank_type == "r":
            increase = fund["dayGrowth"]
        res.append([fund["code"], fund["name"], increase, fund["netWorth"]])
    return res


# 根据基金ID获取涨幅
def get_fund_info_by_id(fund_id, type):
    # type == 0 or 1 日涨幅
    # type == 2 周涨幅
    # type == 3 月涨幅
    # type == 4 年涨幅

    #print(time.time())
    db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
    cursor = db.cursor()
    sql = "select * from api_fund where fund_id='%s'" % (fund_id)
    cursor.execute(sql)
    fund = cursor.fetchone()
    res = dict()
    res["fundId"] = fund[0]
    res["name"] = fund[1]
    res["value"] = fund[-1]
    if type == 0 or type == 1:
        res["increase"] = fund[7]
    elif type == 2:
        res["increase"] = fund[8]
    elif type == 3:
        res["increase"] = fund[9]
    else:
        res["increase"] = fund[12]
    return res

    '''
    print(time.time())
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-05-14", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    res = dict()
    res["fundId"] = fund_id
    res["name"] = fund_info["name"]
    if "netWorth" not in fund_info.keys():
        res["value"] = 0
    else:
        res["value"] = fund_info["netWorth"]
    if type == 0 or type == 1:
        if "dayGrowth" not in fund_info.keys():
            res["increase"] = 0
        else:
            res["increase"] = fund_info["dayGrowth"]
    elif type == 2:
        if "lastWeekGrowth" not in fund_info.keys():
            res["increase"] = 0
        else:
            res["increase"] = fund_info["lastWeekGrowth"]
    elif type == 3:
        res["increase"] = fund_info["lastMonthGrowth"]
    else:
        res["increase"] = fund_info["lastYearGrowth"]
    print(time.time())
    '''
   # return res


# 根据基金ID获取持仓和债券、股票占比
# string  -->  {"position":..., "rate":...}
def get_position_and_rate_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/position?code=" + fund_id, headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    position = []
    rate = []
    data = json.loads(response)["data"]
    if data is None:
        position = []
        rate.append(["stock", 0])
        rate.append(["bond", 0])
        rate.append(["cash", 0])
        return {"position": position, "rate": rate}
    if "stockList" not in data.keys():
        position = []
    else:
        stock_list = json.loads(response)["data"]["stockList"]
        for item in stock_list:
            position.append([item[0], item[1], item[2]])
    rate.append(["stock", data["stock"]])
    rate.append(["bond", data["bond"]])
    rate.append(["cash", data["cash"]])
    return {"position": position, "rate": rate}


# 根据基金ID获取基金规模和净值
def get_price_and_scale_by_id(fund_id, number):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-04-15", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    data = fund_info["netWorthData"]
    res = dict()
    price = []
    scale = []
    for item in data[-number:]:
        price.append([item[0][5:], item[1], item[2]])   # 日期、净值、涨幅
    if "netWorthData" not in fund_info.keys():
        scale = [0, 0]
    else:
        scale = [fund_info["fundScale"], fund_info["netWorthDate"]]
    return {"price": price, "scale": scale}

if __name__ == '__main__':
    print(get_fund_info_by_id('000001',0))